import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程记录列表合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
// import StudentABI from '../contract/ABIs/Student.json'; // 学生合约 ABI
import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js" // 课程记录列表合约地址

const Admin_GetTotalCredit = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [credit, setcredit] = useState('');//用于存储从合约中获取的总学分
    const [StudentAddress, setStudentAddress] = useState('');//用户地址
    // const [Totalcredit, setTotalcredit] = useState('');// 用于存储从合约中获取的总学分




    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    const getTotalCredit = async () => {
        if (contractCourseRecordList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);
                // 调用智能合约的某个函数
                await contractCourseRecordList.methods.getTotalCredit(StudentAddress).send({ from: fromAddress }).then((result) => {
                    console.log(result)
                    setcredit(Number(result).toString())
                    console.log("result:", result);

                })
                alert("计算成功")
            } catch (error) {
                console.error(error);
                alert("计算失败")
            }
        }
    };
    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div>

                    <Admin_creditsNavBar address={address} />

                    <main className="page hire-me-page">
                        <section className="portfolio-block hire-me">
                            <div className="container">
                                <div className="border rounded border-0 shadow-lg p-3 p-md-5" data-bs-theme="light">
                                    <h1>计算总学分</h1>
                                    <div className="mb-3">
                                        <label className="form-label" htmlFor="name">学生地址</label>
                                        <input className="form-control item" id="name" type="text" placeholder="用户名" value={StudentAddress} onChange={(e) => setStudentAddress(e.target.value)} />
                                    </div>

                                    <div className="mb-3 mt-4">
                                        <button className="btn btn-primary btn-lg d-block w-100" onClick={getTotalCredit}>获取</button>
                                    </div>
                                    {credit && (
                                        <div className="mb-3">
                                            <label className="form-label" htmlFor="name">总学分：</label>
                                            <label className="form-label" htmlFor="name">{credit}</label>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </section>
                    </main>
                </div>
            )}
        </div>
    )
}

export default Admin_GetTotalCredit